/*
 * Copyright (C) 2010-2014 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package trs.wmata.api;

import trs.wmata.api.Cache.CacheEntry;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xml.sax.InputSource;

public final class CachedApiSource extends ApiSource {
    // private static final String TAG = "CachedApiSource";
    private CacheEntry cacheEntry = null;
    private final String cacheKey;

    public CachedApiSource(final String urlStr) {
        this(urlStr, urlStr);
    }

    public CachedApiSource(final String urlStr, final String cacheKey) {
        super(urlStr);

        if (cacheKey != null) {
            this.cacheKey = cacheKey;
        } else {
            this.cacheKey = urlStr;
        }
    }

    @Override
    public void openConnection() throws IOException {
    }

    @Override
    public InputSource getInputSource() throws IOException {
        // long startTime = System.currentTimeMillis();
        HttpURLConnection c = null;

        final String content;

        cacheEntry = Cache.getFromCache(cacheKey);

        if ((cacheEntry != null) && (cacheEntry.getResponseCode() == 200)) {
            content = cacheEntry.getContent();

            // Log.d(TAG, "Elapsed time 1|" + (System.currentTimeMillis() -
            // startTime) + "," + urlStr);
        } else {
            final URL url = new URL(urlStr);
            c = (HttpURLConnection) url.openConnection();
            c.setReadTimeout(READ_TIMEOUT_MILLIS);

            final StringBuilder buff = new StringBuilder();
            final InputStream inputStream = c.getInputStream();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), BUF_SIZE);

            try {
                String s;

                while ((s = reader.readLine()) != null) {
                    buff.append(s);
                }
            } finally {
                reader.close();
            }

            content = buff.toString();

            cacheEntry = Cache.addToCache(cacheKey, content, c.getResponseCode(), c.getResponseMessage());

            // Log.d(TAG, "Elapsed time 2|" + (System.currentTimeMillis() -
            // startTime) + "," + urlStr);
        }

        return new InputSource(new StringReader(content));
    }

    @Override
    public int getResponseCode() throws IOException {
        return (cacheEntry != null) ? cacheEntry.getResponseCode() : (-500);
    }

    @Override
    public String getResponseMessage() throws IOException {
        return (cacheEntry != null) ? cacheEntry.getResponseMessage() : "";
    }

    @Override
    public void disconnect() {
    }
}
